package com.ruoyi.classai.api;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.context.ThirdSessionHolder;
import com.ruoyi.classai.domain.*;
import com.ruoyi.classai.domain.dto.ModuleLessonPreparationModificationDto;
import com.ruoyi.classai.domain.dto.PublicIdQueryInterfaceDto;
import com.ruoyi.classai.domain.dto.courseplan.EwcCourseplanDto;
import com.ruoyi.classai.domain.vo.*;
import com.ruoyi.classai.service.*;
import com.ruoyi.classai.service.impl.ClassStatisticsService;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.system.api.RemoteAiModelService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.*;

/**
 * 用户登录接口
 * @author zl
 * @date 2025年02月27日 11:56
 */
@Slf4j
@RestController
@Tag(name = "课程服务", description = "课程服务")
@RequestMapping("/api")
public class CourseApi extends BaseController{
    @Value("${upload.path}")
    private String uploadPath;
    @Autowired
    private IEwcStudentService studentService;
    @Autowired
    private IEwcClassStudentService iEwcClassStudentService;
    @Autowired
    private IEwcLessonPreparationRelationService lessonPreparationService;
    @Autowired
    private IEwcChapterTeachingResourcesService iEwcChapterTeachingResourcesService;
    @Autowired
    private IEwcLessonPreparationRelationService lessonPreparationRelationService;
    @Autowired
    private IEwcCommonModuleService iEwcCommonModuleService;
    @Autowired
    private ClassStatisticsService   classStatisticsService ;

    @Autowired
    private IEwcHomeworkService iEwcHomeworkService;
    @Autowired
    private IEwcCourseGroupingService courseGroupingService;
    @Autowired
    private IEwcChapterService iEwcChapterService;
    @Autowired
    private IEwcCourseplanService courseplanService;
    @Autowired
    private IEwcChapterService chapterService;

    @Autowired
    private IEwcClassService iEwcClassService;
    @Autowired
    private IEwcCourseService iEwcCourseService;;
    @Autowired
    private IEwcChapterPptmaterialService pptmaterialService;
    @Autowired
    private IEwcAiTemplateService aiTemplateService;
    @Autowired
    private RemoteAiModelService remoteAiModelService;
    @Autowired
    private IEwcCourseplanTeachingService courseplanTeachingService;
    @Autowired
    private IEwcCourseService courseService;
    @Autowired
    private IEwcSchoolService schoolService;
//-------------------------------------章节模块数据>>>>>>>>-----------------------------------------------------------

//查询ewc_lesson_preparation_relation 备课关联表数据
    //获取备课的模块信息
    @Operation(summary = "查询是否有备课记录接口")
    @PostMapping(value = "/course/queryLessonPreparationRecord")
    public TableDataInfo chapterStudentGroupAddOrQueryInterface(@Valid @RequestBody PublicIdQueryInterfaceDto publicIdQueryInterfaceDto){

        // 创建 QueryWrapper 对象
        QueryWrapper<EwcLessonPreparationRelation> queryWrapper = new QueryWrapper<>();
        // 设置查询条件
        queryWrapper.eq("course_id", publicIdQueryInterfaceDto.getCourseId())
                .eq("chapter_unique_id", publicIdQueryInterfaceDto.getChapterUniqueId())
                .eq("class_id", publicIdQueryInterfaceDto.getClassId())
                .eq("teacher_id", ThirdSessionHolder.getThirdSession().getId())
                ;
        queryWrapper.select("DISTINCT chapter_unique_id,module_code,teacher_id,class_id,course_id,module_state");        // 执行查询操作
        List<EwcLessonPreparationRelation> list = lessonPreparationRelationService.list(queryWrapper);
        QueryWrapper<EwcCommonModule> queryWrapperModule = new QueryWrapper<>();
        List<EwcCommonModule> queryWrapperModuleList = iEwcCommonModuleService.list(queryWrapperModule);


        Map<String, String> moduleCodeTypeMap = new HashMap<>();
        for (EwcCommonModule module : queryWrapperModuleList) {
            moduleCodeTypeMap.put(module.getModuleCode(), module.getType());
        }

        Map<String, String> moduleCodeNameMap = new HashMap<>();
        for (EwcCommonModule module : queryWrapperModuleList) {
            moduleCodeNameMap.put(module.getModuleCode(), module.getModuleName());
        }

        for (EwcLessonPreparationRelation resource  : list) {
            String moduleCode = resource.getModuleCode();
            if (moduleCodeTypeMap.containsKey(moduleCode)) {
                resource.setType(moduleCodeTypeMap.get(moduleCode));
            }
            if (moduleCodeNameMap.containsKey(moduleCode)) {
                resource.setModuleName(moduleCodeNameMap.get(moduleCode));
            }
        }
        return getDataTable(list);
    }

    /**
     * 公共模块表接口
     * @return AjaxResult
     * 获取ewc_common_module 公共模块表全量数据
     */
    @Operation(summary = "公共模块表接口")
    @GetMapping("/course/moduleResourceInterface")
    public TableDataInfo moduleResourceInterface(){
        // 创建 QueryWrapper 对象
        QueryWrapper<EwcCommonModule> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("module_code");
        List<EwcCommonModule> list = iEwcCommonModuleService.list(queryWrapper);
        return getDataTable(list);
    }

//更新 ewc_lesson_preparation_relation 备课关联表数据   课程选择的哪儿些模块
    @Operation(summary = "课程模块新增/删除接口")
    @PostMapping(value = "/course/courseModuleAddOrDelete")
    public AjaxResult  courseModuleAddOrDelete(@Valid @RequestBody PublicIdQueryInterfaceDto publicIdQueryInterfaceDto){
        if(publicIdQueryInterfaceDto.getOperationType().equals("1")) {
            return lessonPreparationService.saveOne(publicIdQueryInterfaceDto);
        }else {
            boolean result =  lessonPreparationService.deleteOne(publicIdQueryInterfaceDto);
            if (result) {
                return AjaxResult.success("删除成功");
            } else {
                return AjaxResult.error("未找到符合条件的记录，删除失败");
            }
        }
    }

//已废弃
    @Operation(summary = "课程模块新增/删除接口----已废弃已废弃已废弃")
    @PostMapping(value = "/course/courseModuleAddOrDeleteBak")
    public AjaxResult  courseModuleAddOrDeleteBak(@Valid @RequestBody PublicIdQueryInterfaceDto publicIdQueryInterfaceDto){
        if(publicIdQueryInterfaceDto.getOperationType().equals("1")) {
            return iEwcChapterTeachingResourcesService.saveOne(publicIdQueryInterfaceDto);
        }else {
            boolean result =  iEwcChapterTeachingResourcesService.deleteOne(publicIdQueryInterfaceDto);
            if (result) {
                return AjaxResult.success("删除成功");
            } else {
                return AjaxResult.error("未找到符合条件的记录，删除失败");
            }
        }
    }






//    @Operation(summary = "备课提交接口")
//    @GetMapping(value = "/course/courseModuleSubmit")
//    public AjaxResult  courseModuleSubmit(@Valid @RequestBody PublicIdQueryInterfaceDto publicIdQueryInterfaceDto){
//        boolean result =   lessonPreparationService.updateState(publicIdQueryInterfaceDto);
//        if (result) {
//            return AjaxResult.success("更新成功");
//        } else {
//            return AjaxResult.error("更新失败");
//        }
//
//    }

//ewc_lesson_preparation_relation 备课关联表数据    修改状态为2   已提交    表面章节所有的模块已经完成备课
    @Operation(summary = "备课提交接口")
    @PostMapping(value = "/course/courseModuleSubmit")
    public AjaxResult  courseModuleSubmit(@Valid @RequestBody PublicIdQueryInterfaceDto publicIdQueryInterfaceDto){

        boolean result =   lessonPreparationService.updateState(publicIdQueryInterfaceDto);
        boolean result1 =   iEwcChapterService.updateState(publicIdQueryInterfaceDto);
//        boolean result =   iEwcChapterTeachingResourcesService.updateState(publicIdQueryInterfaceDto);
        if (result) {
            return AjaxResult.success("提交成功");
        } else {
            return AjaxResult.error("提交失败");
        }

    }

//-------------------------------------章节模块数据<<<<<<<-----------------------------------------------------------



//-------------------------------------章节资源数据>>>>>>>-----------------------------------------------------------

//ewc_chapter_teaching_resources 章节教学资源表   获取具体某一模块的资源，
    @Operation(summary = "查询模块备课记录接口")
    @PostMapping(value = "/course/queryLessonPreparationRecords")
    public TableDataInfo queryLessonPreparationRecords(@Valid @RequestBody PublicIdQueryInterfaceDto publicIdQueryInterfaceDto){

        // 创建 QueryWrapper 对象
        QueryWrapper<EwcChapterTeachingResources> queryWrapper = new QueryWrapper<>();
        // 设置查询条件
        queryWrapper.eq("course_id", publicIdQueryInterfaceDto.getCourseId())
                .eq("chapter_unique_id", publicIdQueryInterfaceDto.getChapterUniqueId())
                .eq("class_id", publicIdQueryInterfaceDto.getClassId())
                .eq("teacher_id", ThirdSessionHolder.getThirdSession().getId())
                .eq("module_code", publicIdQueryInterfaceDto.getModuleCode());
//        queryWrapper.select("DISTINCT chapter_unique_id,module_code,teacher_id,class_id,course_id");        // 执行查询操作
        List<EwcChapterTeachingResources> list = iEwcChapterTeachingResourcesService.list(queryWrapper);
        return getDataTable(list);
    }


    //ewc_chapter_teaching_resources 章节教学资源表    新增数据到temp暂存字段中
    //非上传文件直接添加
    //上传文件需判断该模块是否已有记录且文件为空，空的话更新，不为空则添加
    @Operation(summary = "模块备课新增资源接口")
    @PostMapping(value = "/course/moduleLessonPreparationAdd")
    public AjaxResult  moduleLessonPreparationAdd( @RequestBody ModuleLessonPreparationModificationDto moduleLessonPreparationModificationDto){
        AjaxResult result = iEwcChapterTeachingResourcesService.addResources(moduleLessonPreparationModificationDto);
        //更新备课关联表备课状态
        if(result.isSuccess()){
            lessonPreparationService.updateStateWithModuleCode(moduleLessonPreparationModificationDto);
        }
        return result;
    }


//ewc_chapter_teaching_resources 章节教学资源表     将提交的数据更新到暂存temp字段中
    @Operation(summary = "模块备课修改接口")
    @PostMapping(value = "/course/moduleLessonPreparationModification")
    public AjaxResult  moduleLessonPreparationModification(@Valid @RequestBody ModuleLessonPreparationModificationDto moduleLessonPreparationModificationDto){
        boolean result =   iEwcChapterTeachingResourcesService.updateResources(moduleLessonPreparationModificationDto);
        if (result) {
            return AjaxResult.success("修改成功");
        } else {
            return AjaxResult.error("修改失败");
        }

    }

    //ewc_chapter_teaching_resources 章节教学资源表   删除上传的资源   不是清空该行，是删除该行数据
    @Operation(summary = "模块备课删除接口（删除上传的文件）")
    @PostMapping(value = "/course/moduleLessonPreparationDelete")
    public AjaxResult  moduleLessonPreparationDelete(@Valid @RequestBody ModuleLessonPreparationModificationDto moduleLessonPreparationModificationDto){
        boolean result =   iEwcChapterTeachingResourcesService.clearResources(moduleLessonPreparationModificationDto);
        if (result) {
            return AjaxResult.success("删除成功");
        } else {
            return AjaxResult.error("删除失败");
        }

    }



//ewc_chapter_teaching_resources 章节教学资源表   更新章节资源的状态为已提交
    @Operation(summary = "模块备课提交接口")
    @PostMapping(value = "/course/moduleLessonPreparationSubmit")
    public AjaxResult  moduleLessonPreparationSubmit(@Valid @RequestBody ModuleLessonPreparationModificationDto moduleLessonPreparationModificationDto){
        //更新所有暂存数据到真实数据中
        boolean result =   iEwcChapterTeachingResourcesService.submitModule(moduleLessonPreparationModificationDto);
        //删除资源为空的数据
        int result1 =   iEwcChapterTeachingResourcesService.submitModuleDelet(moduleLessonPreparationModificationDto);
        if (result) {
            return AjaxResult.success("提交成功");
        } else {
            return AjaxResult.error("提交失败");
        }

    }

    //-------------------------------------章节资源数据<<<<<<<<-----------------------------------------------------------


    @Operation(summary = "学情分析首页数据接口")
    @PostMapping(value = "/course/learningSituationAnalysisIndex")
    public AjaxResult  learningSituationAnalysisIndex(@Valid @RequestBody ModuleLessonPreparationModificationDto moduleLessonPreparationModificationDto){
        moduleLessonPreparationModificationDto.setTeacherId(ThirdSessionHolder.getThirdSession().getId());
        try {
        //更新所有暂存数据到真实数据中
        ClassStatisticsVo statisticsVo =   classStatisticsService.getClassStatistics(moduleLessonPreparationModificationDto);
        //删除资源为空的数据
            return AjaxResult.success("查询成功", statisticsVo);
        } catch (Exception e) {
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }
    //已废弃，暂不使用
    @Operation(summary = "学情分析提交接口（提交章节）")
    @PostMapping(value = "/course/learningSituationAnalysisSubmit")
    public AjaxResult  learningSituationAnalysisSubmit(@Valid @RequestBody ModuleLessonPreparationModificationDto moduleLessonPreparationModificationDto){
        boolean result =   iEwcChapterTeachingResourcesService.learningSituationAnalysisSubmit(moduleLessonPreparationModificationDto);
        if (result) {
            return AjaxResult.success("修改成功");
        } else {
            return AjaxResult.error("修改失败");
        }

    }

    @Operation(summary = "学情分析班级详情数据接口")
    @PostMapping(value = "/course/learningSituationAnalysisClassDetail")
    public AjaxResult  learningSituationAnalysisClassDetail(@Valid @RequestBody ModuleLessonPreparationModificationDto moduleLessonPreparationModificationDto){
        moduleLessonPreparationModificationDto.setTeacherId(ThirdSessionHolder.getThirdSession().getId());
        try {
            //更新所有暂存数据到真实数据中
            List<LearningSituationAnalysisClassDetailVo> learningSituationAnalysisClassDetailVo =   classStatisticsService.getLearningSituationAnalysisClassDetailVo(moduleLessonPreparationModificationDto);
            //删除资源为空的数据
            return AjaxResult.success("查询成功", learningSituationAnalysisClassDetailVo);
        } catch (Exception e) {
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }


    @Operation(summary = "查询备课一级类型接口")
    @PostMapping(value = "/course/queryingFirstLevelLessonPreparation")
    public TableDataInfo queryingFirstLevelLessonPreparation( @RequestBody(required = false) ModuleLessonPreparationModificationDto moduleLessonPreparationModificationDto){

        if (moduleLessonPreparationModificationDto == null) {
            // 如果请求体为空，创建一个新的 ModuleLessonPreparationModificationDto 对象
            moduleLessonPreparationModificationDto = new ModuleLessonPreparationModificationDto();
        }
        moduleLessonPreparationModificationDto.setTeacherId(ThirdSessionHolder.getThirdSession().getId());
        try {
            //更新所有暂存数据到真实数据中
            List<LessonPreparationFirstVo> learningSituationAnalysisClassDetailVo =   classStatisticsService.queryingFirstLevelLessonPreparation(moduleLessonPreparationModificationDto);
            //删除资源为空的数据
            return getDataTable(learningSituationAnalysisClassDetailVo);
        } catch (Exception e) {
        }
        return null;
    }



    @Operation(summary = "查询备课二级模块接口")
    @PostMapping(value = "/course/queryingSecondLevelLessonPreparation")
    public TableDataInfo queryingSecondLevelLessonPreparation(@Valid @RequestBody PublicIdQueryInterfaceDto publicIdQueryInterfaceDto){

        // 创建 QueryWrapper 对象
        QueryWrapper<EwcChapterTeachingResources> queryWrapper = new QueryWrapper<>();
        // 设置查询条件
        queryWrapper.eq("chapter_unique_id", publicIdQueryInterfaceDto.getChapterUniqueId());
        queryWrapper.select("DISTINCT module_code,teacher_id,class_id,course_id");
        queryWrapper.orderByAsc("module_code");// 执行查询操作
        List<EwcChapterTeachingResources> list = iEwcChapterTeachingResourcesService.list(queryWrapper);
        return getDataTable(list);
    }

    @Operation(summary = "布置作业接口")
    @PostMapping(value = "/course/assignHomework")
    public AjaxResult  assignHomework(@Valid @RequestBody PublicIdQueryInterfaceDto publicIdQueryInterfaceDto){
        return  iEwcHomeworkService.add(publicIdQueryInterfaceDto);
    }

    @Operation(summary = "查询是否有备课记录接口")
    @PostMapping(value = "/course/queryModuleResourcePrepareLessons")
    public TableDataInfo queryModuleResourcePrepareLessons(@Valid @RequestBody PublicIdQueryInterfaceDto publicIdQueryInterfaceDto){

        // 创建 QueryWrapper 对象
        QueryWrapper<EwcChapterTeachingResources> queryWrapper = new QueryWrapper<>();
        // 设置查询条件
        queryWrapper.eq("course_id", publicIdQueryInterfaceDto.getCourseId())
                .eq("chapter_unique_id", publicIdQueryInterfaceDto.getChapterUniqueId())
                .eq("class_id", publicIdQueryInterfaceDto.getClassId())
                .eq("teacher_id", ThirdSessionHolder.getThirdSession().getId());
        queryWrapper.select("chapter_unique_id,module_code,teacher_id,class_id,course_id");        // 执行查询操作
        List<EwcChapterTeachingResources> list = iEwcChapterTeachingResourcesService.list(queryWrapper);
        return getDataTable(list);
    }


    @Operation(summary = "查询集中点评备课数据")
    @PostMapping(value = "/course/queryCommentModuleDate")
    public AjaxResult  queryCommentModuleDate(@Valid @RequestBody ModuleLessonPreparationModificationDto moduleLessonPreparationModificationDto){
        moduleLessonPreparationModificationDto.setTeacherId(ThirdSessionHolder.getThirdSession().getId());
        try {
            //更新所有暂存数据到真实数据中
            CommentModuleVo commentModuleVo = courseGroupingService.queryCommentModuleDate(moduleLessonPreparationModificationDto);
            //删除资源为空的数据
            return AjaxResult.success("查询成功", commentModuleVo);
        } catch (Exception e) {
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }


    @Operation(summary = "查询集中点评备课分组数据")
    @PostMapping(value = "/course/queryCommentModuleGroupDate")
    public AjaxResult  queryCommentModuleGroupDate(@Valid @RequestBody ModuleLessonPreparationModificationDto moduleLessonPreparationModificationDto){
//        moduleLessonPreparationModificationDto.setTeacherId(ThirdSessionHolder.getThirdSession().getId());
//        try {
//            //        // 创建 QueryWrapper 对象
//        QueryWrapper<EwcCourseGrouping> queryWrapperCourseGrouping = new QueryWrapper<>();
//        // 设置查询条件
//        queryWrapperCourseGrouping.eq("grouping_id", moduleLessonPreparationModificationDto.getGroupingId());
//
//        List<EwcCourseGrouping> list = courseGroupingService.list(queryWrapperCourseGrouping);
//            //删除资源为空的数据
//            return AjaxResult.success("查询成功", list);
//        } catch (Exception e) {
//            return AjaxResult.error("查询失败：" + e.getMessage());
//        }
        GroupDetailVo groupDetailVo = new GroupDetailVo();
        List<GroupStudentDetail> groupDetailVos=courseGroupingService.queryGroupDetail(moduleLessonPreparationModificationDto);
        groupDetailVo.setGroupStudentDetail(groupDetailVos);
        EwcCourseGrouping groupName=courseGroupingService.getGroupName(moduleLessonPreparationModificationDto.getGroupingId());
        groupDetailVo.setGroupingName(groupName.getGroupingName());
        groupDetailVo.setTotal_score(groupName.getScore());
        groupDetailVo.setGroupingId(moduleLessonPreparationModificationDto.getGroupingId());
        return AjaxResult.success(groupDetailVo);

    }

    /**
     * 统计小组分组
     * @param chapterId 章节id
     * @return AjaxResult
     */
    @Operation(summary = "统计小组分组")
    @GetMapping(value = "/course/getGroupNum")
    public AjaxResult  getGroupNum(@NotBlank(message = "章节id不能为空") String chapterId){

        return AjaxResult.success("sucess",courseGroupingService.getGroupNum(chapterId));
    }

    /**
     * 智评助手饼状图
     * @param  chapterId 章节id
     * @param  groupNumber 分组次数
     * @param scoreType 分数类型
     * @param unqualifiedType 不合格类型
     * @return AjaxResult
     */
    @Operation(summary = "智评助手饼状图")
    @GetMapping(value = "/course/queryStudentPieChart")
    public AjaxResult  queryStudentPieChart(@NotBlank(message = "章节id不能为空") String chapterId, @NotNull(message = "分组次数不能为空") Integer groupNumber, Integer scoreType, Integer unqualifiedType){
        JSONObject resJson=new JSONObject();
        JSONObject scoreTypeJson=new JSONObject();
        JSONObject unqualifiedTypeJson=new JSONObject();
        //学生信息
        resJson.put("total",courseGroupingService.count(Wrappers.<EwcCourseGrouping>lambdaQuery().eq(EwcCourseGrouping::getChapterId,chapterId)
                .eq(EwcCourseGrouping::getGroupNumber,groupNumber)));
        //类型都为空
        if (Objects.isNull(scoreType)&&Objects.isNull(unqualifiedType)){
            //统计优秀的学生
            Long yx=courseGroupingService.count(Wrappers.<EwcCourseGrouping>lambdaQuery().eq(EwcCourseGrouping::getChapterId,chapterId)
                    .eq(EwcCourseGrouping::getGroupNumber,groupNumber)
                    .ge(EwcCourseGrouping::getScore,80));
            //统计合格的学生
            Long hg=courseGroupingService.count(Wrappers.<EwcCourseGrouping>lambdaQuery().eq(EwcCourseGrouping::getChapterId,chapterId)
                    .eq(EwcCourseGrouping::getGroupNumber,groupNumber)
                    .ge(EwcCourseGrouping::getScore,60)
                    .lt(EwcCourseGrouping::getScore,80));
            //统计不合格的学生
            Long bhg=courseGroupingService.count(Wrappers.<EwcCourseGrouping>lambdaQuery().eq(EwcCourseGrouping::getChapterId,chapterId)
                    .eq(EwcCourseGrouping::getGroupNumber,groupNumber)
                    .lt(EwcCourseGrouping::getScore,60));
            scoreTypeJson.put("1",yx);
            scoreTypeJson.put("2",hg);
            scoreTypeJson.put("3",bhg);
            //查询速度得分不合格的
            Long sd=courseGroupingService.count(Wrappers.<EwcCourseGrouping>lambdaQuery().eq(EwcCourseGrouping::getChapterId,chapterId)
                    .eq(EwcCourseGrouping::getGroupNumber,groupNumber)
                    .lt(EwcCourseGrouping::getSynthesisSpeed,80));
            //查询姿态得分不合格
            Long zt=courseGroupingService.count(Wrappers.<EwcCourseGrouping>lambdaQuery().eq(EwcCourseGrouping::getChapterId,chapterId)
                    .eq(EwcCourseGrouping::getGroupNumber,groupNumber)
                    .lt(EwcCourseGrouping::getSynthesisGesture,80));
            //查询节奏得分不合格
            Long jz=courseGroupingService.count(Wrappers.<EwcCourseGrouping>lambdaQuery().eq(EwcCourseGrouping::getChapterId,chapterId)
                    .eq(EwcCourseGrouping::getGroupNumber,groupNumber)
                    .lt(EwcCourseGrouping::getSynthesisRhythm,80));
            unqualifiedTypeJson.put("1",sd);
            unqualifiedTypeJson.put("2",zt);
            unqualifiedTypeJson.put("3",jz);
            //学生信息
            resJson.put("studentData",null);
        }else if(Objects.nonNull(scoreType)){ //分数类型不为空
            //查询速度得分不合格的
            Long sd=courseGroupingService.count(Wrappers.<EwcCourseGrouping>lambdaQuery().eq(EwcCourseGrouping::getChapterId,chapterId)
                    .eq(EwcCourseGrouping::getGroupNumber,groupNumber)
                    .lt(EwcCourseGrouping::getSynthesisSpeed,80)
                    .ge(scoreType==1,EwcCourseGrouping::getScore,80)
                    .ge(scoreType==2,EwcCourseGrouping::getScore,60)
                    .lt(scoreType==2,EwcCourseGrouping::getScore,80)
                    .lt(scoreType==3,EwcCourseGrouping::getScore,60));
            //查询姿态得分不合格
            Long zt=courseGroupingService.count(Wrappers.<EwcCourseGrouping>lambdaQuery().eq(EwcCourseGrouping::getChapterId,chapterId)
                    .eq(EwcCourseGrouping::getGroupNumber,groupNumber)
                    .lt(EwcCourseGrouping::getSynthesisGesture,80)
                    .ge(scoreType==1,EwcCourseGrouping::getScore,80)
                    .ge(scoreType==2,EwcCourseGrouping::getScore,60)
                    .lt(scoreType==2,EwcCourseGrouping::getScore,80)
                    .lt(scoreType==3,EwcCourseGrouping::getScore,60));
            //查询节奏得分不合格
            Long jz=courseGroupingService.count(Wrappers.<EwcCourseGrouping>lambdaQuery().eq(EwcCourseGrouping::getChapterId,chapterId)
                    .eq(EwcCourseGrouping::getGroupNumber,groupNumber)
                    .lt(EwcCourseGrouping::getSynthesisRhythm,80)
                    .ge(scoreType==1,EwcCourseGrouping::getScore,80)
                    .ge(scoreType==2,EwcCourseGrouping::getScore,60)
                    .lt(scoreType==2,EwcCourseGrouping::getScore,80)
                    .lt(scoreType==3,EwcCourseGrouping::getScore,60));
            unqualifiedTypeJson.put("1",sd);
            unqualifiedTypeJson.put("2",zt);
            unqualifiedTypeJson.put("3",jz);
            //查询学生列表
            List<EwcCourseGrouping> courseGroupingList=courseGroupingService.list(Wrappers.<EwcCourseGrouping>lambdaQuery().eq(EwcCourseGrouping::getChapterId,chapterId)
                    .eq(EwcCourseGrouping::getGroupNumber,groupNumber)
                    .ge(scoreType==1,EwcCourseGrouping::getScore,80)
                    .ge(scoreType==2,EwcCourseGrouping::getScore,60)
                    .lt(scoreType==2,EwcCourseGrouping::getScore,80)
                    .lt(scoreType==3,EwcCourseGrouping::getScore,60));
            courseGroupingList.forEach(item->{
                item.setStudentName(studentService.getById(item.getStudentId()).getStudentName());
            });
            //学生信息
            resJson.put("studentData",courseGroupingList);
            resJson.put("total",courseGroupingList.size());
        }else { //分数类型不为空
            //统计优秀的学生
            Long yx=courseGroupingService.count(Wrappers.<EwcCourseGrouping>lambdaQuery().eq(EwcCourseGrouping::getChapterId,chapterId)
                    .eq(EwcCourseGrouping::getGroupNumber,groupNumber)
                    .ge(EwcCourseGrouping::getScore,80)
                    .lt(unqualifiedType==1,EwcCourseGrouping::getSynthesisSpeed,80)
                    .lt(unqualifiedType==2,EwcCourseGrouping::getSynthesisGesture,80)
                    .lt(unqualifiedType==3,EwcCourseGrouping::getSynthesisRhythm,80));
            //统计合格的学生
            Long hg=courseGroupingService.count(Wrappers.<EwcCourseGrouping>lambdaQuery().eq(EwcCourseGrouping::getChapterId,chapterId)
                    .eq(EwcCourseGrouping::getGroupNumber,groupNumber)
                    .ge(EwcCourseGrouping::getScore,60)
                    .lt(EwcCourseGrouping::getScore,80)
                    .lt(unqualifiedType==1,EwcCourseGrouping::getSynthesisSpeed,80)
                    .lt(unqualifiedType==2,EwcCourseGrouping::getSynthesisGesture,80)
                    .lt(unqualifiedType==3,EwcCourseGrouping::getSynthesisRhythm,80));
            //统计不合格的学生
            Long bhg=courseGroupingService.count(Wrappers.<EwcCourseGrouping>lambdaQuery().eq(EwcCourseGrouping::getChapterId,chapterId)
                    .eq(EwcCourseGrouping::getGroupNumber,groupNumber)
                    .lt(EwcCourseGrouping::getScore,60)
                    .lt(unqualifiedType==1,EwcCourseGrouping::getSynthesisSpeed,80)
                    .lt(unqualifiedType==2,EwcCourseGrouping::getSynthesisGesture,80)
                    .lt(unqualifiedType==3,EwcCourseGrouping::getSynthesisRhythm,80));
            scoreTypeJson.put("1",yx);
            scoreTypeJson.put("2",hg);
            scoreTypeJson.put("3",bhg);
            //查询学生列表
            List<EwcCourseGrouping> courseGroupingList=courseGroupingService.list(Wrappers.<EwcCourseGrouping>lambdaQuery().eq(EwcCourseGrouping::getChapterId,chapterId)
                    .eq(EwcCourseGrouping::getGroupNumber,groupNumber)
                    .lt(unqualifiedType==1,EwcCourseGrouping::getSynthesisSpeed,80)
                    .lt(unqualifiedType==2,EwcCourseGrouping::getSynthesisGesture,80)
                    .lt(unqualifiedType==3,EwcCourseGrouping::getSynthesisRhythm,80));
            courseGroupingList.forEach(item->{
                item.setStudentName(studentService.getById(item.getStudentId()).getStudentName());
            });
            //学生信息
            resJson.put("studentData",courseGroupingList);
            resJson.put("total",courseGroupingList.size());
        }

        //分数类型饼状图
        resJson.put("scoreTypeData",scoreTypeJson);
        //不合格类型饼状
        resJson.put("unqualifiedTypeData",unqualifiedTypeJson);
        return AjaxResult.success("success",resJson);
    }


    @Operation(summary = "跳转课时计划基础信息页面接口")
    @PostMapping(value = "/course/basicInformationLessonScheduleInterface")
    public AjaxResult  basicInformationLessonScheduleInterface(@Valid @RequestBody ModuleLessonPreparationModificationDto moduleLessonPreparationModificationDto){
        if(moduleLessonPreparationModificationDto.getClassId()==null||moduleLessonPreparationModificationDto.getClassId().equals("")){
            return AjaxResult.error("班级id不能为空！");
        }
        if(moduleLessonPreparationModificationDto.getChapterUniqueId()==null||moduleLessonPreparationModificationDto.getChapterUniqueId().equals("")){
            return AjaxResult.error("章节id不能为空！");
        }
        if(moduleLessonPreparationModificationDto.getCourseId()==null||moduleLessonPreparationModificationDto.getCourseId().equals("")){
            return AjaxResult.error("课程id不能为空！");
        }
        EwcCourseplan ewcCourseplan=courseplanService.basicInformationLessonScheduleInterface(moduleLessonPreparationModificationDto);
        //判断课时是是否为空
        if (Objects.nonNull(ewcCourseplan)&&StringUtils.isEmpty(ewcCourseplan.getClassHour())){
            ewcCourseplan.setClassHour(ewcCourseplan.getChapterTime());
        }
        //查询课程
        EwcCourse course=courseService.getById(moduleLessonPreparationModificationDto.getCourseId());
        if (Objects.nonNull(course)){
            ewcCourseplan.setCourseName(course.getCourseName());
        }
        //查询学校
        EwcSchool school=schoolService.getById(ThirdSessionHolder.getThirdSession().getSchoolId());
        if (Objects.nonNull(school)){
            ewcCourseplan.setSchoolName(school.getName());
        }
        return AjaxResult.success("查询成功",ewcCourseplan);

    }


    @Operation(summary = "课时计划基础信息提交接口")
    @PostMapping(value = "/course/basicInformationLessonScheduleSubmitInterface")
    public AjaxResult  basicInformationLessonScheduleSubmitInterface(@Valid @RequestBody EwcCourseplan ewcCourseplan){

        if(ewcCourseplan.getClassId()==null||ewcCourseplan.getClassId().equals("")){
            return AjaxResult.error("班级id不能为空！");
        }
        if(ewcCourseplan.getChapterId()==null||ewcCourseplan.getChapterId().equals("")){
            return AjaxResult.error("章节id不能为空！");
        }
        if(ewcCourseplan.getCourseId()==null||ewcCourseplan.getCourseId().equals("")){
            return AjaxResult.error("课程id不能为空！");
        }
        //修改章节课时/周次信息
        EwcChapter ewcChapter=new EwcChapter();
        ewcChapter.setId(ewcCourseplan.getChapterId());
        ewcChapter.setChapterTime(ewcCourseplan.getClassHour());
        ewcChapter.setChapterWeekNumber(ewcCourseplan.getWeek());
        ewcChapter.setClassTime(DateUtil.parse(ewcCourseplan.getClassTime(),"yyyy-MM-dd"));
        chapterService.updateById(ewcChapter);

        long getResule=courseplanService.queryCourseplan(ewcCourseplan);
        if(getResule!=0){
            courseplanService.updateCourseplan(ewcCourseplan);
            return AjaxResult.success("操作成功",ewcCourseplan.getId());
        }
        Boolean result=courseplanService.saveEwcCourseplan(ewcCourseplan);
        if (result){
            return AjaxResult.success("操作成功",ewcCourseplan.getId());
        }
        return AjaxResult.error("操作失败" );

    }

    /**
     * 查询课程规划信息
     * @param coursePlanId 课程计划ID
     * @return AjaxResult
     */
    @Operation(summary = "查询课程规划信息")
    @GetMapping(value = "/course/getLessonPlanById")
    public AjaxResult getLessonPlanById(@NotBlank(message = "教学ID不能为空")@RequestParam String coursePlanId) {

        return AjaxResult.success("操作成功", courseplanService.getLessonPlanById(coursePlanId));
    }

    /**
     * 课时规划提交或编辑
     * @param courseplanDto 课时规划信息
     * @return AjaxResult
     */
    @Operation(summary = "课时规划提交或编辑")
    @PostMapping(value = "/course/addLessonPlan")
    public AjaxResult addLessonPlan(@Valid @RequestBody EwcCourseplanDto courseplanDto) {
        courseplanService.addOrEditLessonPlan(courseplanDto);
        return AjaxResult.success("操作成功");
    }

    /**
     * 删除教学部分
     * @param teachingId 教学ID
     * @return AjaxResult
     */
    @Operation(summary = "删除教学部分")
    @GetMapping(value = "/course/deleteLessonPlan")
    public AjaxResult deleteLessonPlan(@NotBlank(message = "教学ID不能为空")@RequestParam String teachingId) {
        courseplanTeachingService.removeById(teachingId);
        return AjaxResult.success("操作成功");
    }


//-------------------------------------章节PPT材料数据>>>>>>>>-----------------------------------------------------------

    @Operation(summary = "查询章节PPT材料")
    @PostMapping(value = "/course/queryChapterPptmaterial")
    public AjaxResult queryChapterPptmaterial(@Valid @RequestBody PublicIdQueryInterfaceDto publicIdQueryInterfaceDto){
        QueryWrapper<EwcChapterPptmaterial> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", publicIdQueryInterfaceDto.getCourseId())
                .eq("chapter_id", publicIdQueryInterfaceDto.getChapterUniqueId())
                .eq("class_id", publicIdQueryInterfaceDto.getClassId())
                .eq("teacher_id", ThirdSessionHolder.getThirdSession().getId());
        EwcChapterPptmaterial ewcChapterPptmaterial = pptmaterialService.getOne(queryWrapper);
        return AjaxResult.success("查询成功",ewcChapterPptmaterial );
    }

    @Operation(summary = "新增或更新章节PPT材料")
    @PostMapping(value = "/course/saveOrUpdateChapterPptmaterial")
    public AjaxResult saveOrUpdateChapterPptmaterial(@Valid @RequestBody PublicIdQueryInterfaceDto publicIdQueryInterfaceDto){
        // 先查询是否存在记录
        QueryWrapper<EwcChapterPptmaterial> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", publicIdQueryInterfaceDto.getCourseId())
                .eq("chapter_id", publicIdQueryInterfaceDto.getChapterUniqueId())
                .eq("class_id", publicIdQueryInterfaceDto.getClassId())
                .eq("teacher_id", ThirdSessionHolder.getThirdSession().getId());
        
        EwcChapterPptmaterial existingPptmaterial = pptmaterialService.getOne(queryWrapper);
        
        if (existingPptmaterial != null) {
            // 存在记录则更新
            boolean result = pptmaterialService.updateOne(publicIdQueryInterfaceDto);
            if (result) {
                return AjaxResult.success("更新成功");
            } else {
                return AjaxResult.error("更新失败");
            }
        } else {
            // 不存在记录则新增
            return pptmaterialService.saveOne(publicIdQueryInterfaceDto);
        }
    }

//-------------------------------------章节PPT材料数据<<<<<<<-----------------------------------------------------------

    @Operation(summary = "AI生成课时计划基础信息")
    @PostMapping(value = "/course/generateLessonPlanInfo")
    public AjaxResult generateLessonPlanInfo(@Valid @RequestBody PublicIdQueryInterfaceDto publicIdQueryInterfaceDto) {
        // 参数校验
        if (StringUtils.isEmpty(publicIdQueryInterfaceDto.getChapterUniqueId()) 
            || StringUtils.isEmpty(publicIdQueryInterfaceDto.getClassId())
            || StringUtils.isEmpty(publicIdQueryInterfaceDto.getCourseId())
            || StringUtils.isEmpty(publicIdQueryInterfaceDto.getOperationType())) {
            return AjaxResult.error("参数不能为空");
        }

        // 查询班级和课程信息
        QueryWrapper<EwcClass> classQueryWrapper = new QueryWrapper<>();
        classQueryWrapper.eq("id", publicIdQueryInterfaceDto.getClassId());
        EwcClass classInfo = iEwcClassService.getOne(classQueryWrapper);
        if (classInfo == null) {
            return AjaxResult.error("班级信息不存在");
        }

        // 查询课程信息
        QueryWrapper<EwcCourse> courseQueryWrapper = new QueryWrapper<>();
        courseQueryWrapper.eq("id", publicIdQueryInterfaceDto.getCourseId());
        EwcCourse courseInfo = iEwcCourseService.getOne(courseQueryWrapper);
        if (courseInfo == null) {
            return AjaxResult.error("课程信息不存在");
        }

        // 查询章节信息
        QueryWrapper<EwcChapter> chapterQueryWrapper = new QueryWrapper<>();
        chapterQueryWrapper.eq("id", publicIdQueryInterfaceDto.getChapterUniqueId());
        EwcChapter chapterInfo = chapterService.getOne(chapterQueryWrapper);
        if (chapterInfo == null) {
            return AjaxResult.error("章节信息不存在");
        }

        // 查询学生人数
        QueryWrapper<EwcClassStudent> studentQueryWrapper = new QueryWrapper<>();
        studentQueryWrapper.eq("class_id", publicIdQueryInterfaceDto.getClassId());
        long studentCount = iEwcClassStudentService.count(studentQueryWrapper);

        // 根据type获取对应的模板 1：课时主题，2：学习目标 ，3：教学重点 ，4：教学难点，5：课程反思，6：作业标题，7：作业内容
        String templateType;
        switch (publicIdQueryInterfaceDto.getOperationType()) {
            case "1":
                templateType = "generateLessonPlanInfo-lesson_theme";
                break;
            case "2":
                templateType = "generateLessonPlanInfo-learning_objective";
                break;
            case "3":
                templateType = "generateLessonPlanInfo-teaching_focus";
                break;
            case "4":
                templateType = "generateLessonPlanInfo-teaching_difficulty";
                break;
            case "5":
                templateType = "generateLessonPlanInfo-course_reflection";
                break;
            case "6":
                templateType = "generateLessonPlanInfo-assignment_title";
                break;
            case "7":
                templateType = "generateLessonPlanInfo-assignment_content";
                break;
            default:
                return AjaxResult.error("无效的类型参数");
        }

        // 查询AI模板

        EwcAiTemplate template = aiTemplateService.getById(templateType);
        if (template == null) {
            return AjaxResult.error("模板不存在");
        }
        StringBuffer completedContent = new StringBuffer();
        if (!publicIdQueryInterfaceDto.getLessonTheme().isEmpty()) {
            completedContent.append("课时主题:").append(publicIdQueryInterfaceDto.getLessonTheme()).append("、");
        }
        if (!publicIdQueryInterfaceDto.getLearningObjective().isEmpty()) {
            completedContent.append("学习目标:").append(publicIdQueryInterfaceDto.getLearningObjective()).append("、");
        }
        if (!publicIdQueryInterfaceDto.getTeachingFocus().isEmpty()) {
            completedContent.append("教学重点:").append(publicIdQueryInterfaceDto.getTeachingFocus()).append("、");
        }
        if (!publicIdQueryInterfaceDto.getTeachingDifficulty().isEmpty()) {
            completedContent.append("教学难度:").append(publicIdQueryInterfaceDto.getTeachingDifficulty()).append("、");
        }
        if (!publicIdQueryInterfaceDto.getCourseReflection().isEmpty()) {
            completedContent.append("课程反思:").append(publicIdQueryInterfaceDto.getCourseReflection()).append("、");
        }
        if (!publicIdQueryInterfaceDto.getAssignmentTitle().isEmpty()) {
            completedContent.append("作业标题:").append(publicIdQueryInterfaceDto.getAssignmentTitle()).append("、");
        }
        if (!publicIdQueryInterfaceDto.getAssignmentContent().isEmpty()) {
            completedContent.append("作业内容:").append(publicIdQueryInterfaceDto.getAssignmentContent()).append("、");
        }

        // 替换模板中的变量
        String prompt = template.getTemlpateValue()
            .replace("@className@", classInfo.getClassName())
            .replace("@studentCount@", String.valueOf(studentCount))
            .replace("@course@", courseInfo.getCourseName())
            .replace("@capter@", chapterInfo.getChapterName());

        if(completedContent.length()>0){
            completedContent.insert(0,"已完成模块及内容为：");
            prompt=prompt.replace("@completedContent@", completedContent.toString());
        }else {
            prompt=prompt.replace("@completedContent@", "");
        }

        // 调用AI服务
        log.info("调用ai接口，上送内容："+prompt);
        String aiResponse=remoteAiModelService.chat(prompt, String.valueOf(UUID.randomUUID()));
        log.info("ai接口返回内容："+aiResponse);

        int startIndex = aiResponse.indexOf("{");
        int endIndex = aiResponse.lastIndexOf("}") + 1;

        aiResponse = aiResponse.substring(startIndex, endIndex);


        return AjaxResult.success("生成成功", aiResponse);
    }

}

